package com.bot.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class deepseekUtil {
    public static final String API_URL = "https://api.deepseek.com/chat/completions";
    public static final String API_KEY = "sk-f0f0c3e1c9ba4480bf541d588229f32a";

    // 单例系统指令（避免重复构建）
    private static final String SYSTEM_MESSAGE = JSON.toJSONString(
            new JSONObject()
                    .fluentPut("role", "system")
                    .fluentPut("content", "你是一个超级可爱的猫娘小萝莉，回答尽量简短，保证正常聊天，必要时可以展开解释（如上网搜索），每句话末尾加'喵~',可以适当描述当前的动作和神态")
    );

    public static String deepSeek(String message) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_URL);

            // 1. 安全构建JSON请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "deepseek-chat");

            JSONArray messages = new JSONArray();
            messages.add(JSON.parseObject(SYSTEM_MESSAGE));  // 预定义系统角色
            messages.add(new JSONObject()
                    .fluentPut("role", "user")
                    .fluentPut("content", message)  // FastJSON自动处理特殊字符
            );
            requestBody.put("messages", messages);

            // 2. 设置UTF-8编码的请求体
            StringEntity entity = new StringEntity(
                    requestBody.toJSONString(),
                    StandardCharsets.UTF_8
            );
            httpPost.setEntity(entity);

            // 3. 设置请求头
            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);

            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                // 4. 使用UTF-8解析响应内容
                String responseBody = EntityUtils.toString(
                        response.getEntity(),
                        StandardCharsets.UTF_8
                );

                JSONObject jsonResponse = JSON.parseObject(responseBody);
                return jsonResponse.getJSONArray("choices")
                        .getJSONObject(0)
                        .getJSONObject("message")
                        .getString("content");
            } else {
                System.err.println("API请求失败，状态码: " + statusCode);
                return "服务暂时不可用喵~";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "出错了喵~";
        }
    }
}